﻿namespace Singer.Shared;

/// <summary>
/// 统一api返回结果模型
/// </summary>
public class CoreApiResult
{
    public const string SuccessCode = "success";
    public const string ErrorCodePre = "error-";
    /// <summary>
    /// 响应编码
    /// </summary>
    public string Code { get; private set; }
    /// <summary>
    /// 返回信息
    /// </summary>
    public string Msg { get; private set; } = "";
    /// <summary>
    /// 当前时间戳
    /// </summary>
    public long Timestamp { get; init; } = DateTimeOffset.Now.ToUnixTimeSeconds();
    /// <summary>
    /// 返回数据
    /// </summary>
    public object? Data { get; private set; }

    public CoreApiResult(string code, string msg = "", object? data = null)
    {
        Code = code;
        Msg = msg;
        Data = data;
    }

    public static CoreApiResult Success(object? data = null)
    {
        return new CoreApiResult(SuccessCode, "", data);
    }

    public static CoreApiResult Error(string msg, string? errorCode = null)
    {
        return new CoreApiResult(FixErrorCode(errorCode), msg);
    }

    public static string FixErrorCode(string? errorCode = null)
    {
        errorCode = string.IsNullOrWhiteSpace(errorCode) ? ErrorCode.Normal.ToString() : errorCode;
        return (ErrorCodePre + errorCode).ToLower();
    }

    public void SetErrorCode(string? errorCode = null)
    {
        Code = FixErrorCode(errorCode);
    }

    public void SetErrorCode(ErrorCode? errorCode = null) 
    {
        Code = FixErrorCode(errorCode?.ToString());
    }
}
